# CCN::Voicemail.pm
# Copyright (C) 2006  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information visit http://carrierclass.net/
#
package CCN::Voicemail;
use strict; use warnings;

# -------- Voicemail synchronization toolbox -------

# -------- vm synchronization -------

sub find_messages($$$$)
{
    my ($hash,$vmpath,$enterprise,$extension) = @_;
    
    return "Usage: find_messages(hashref,vmpath,enterprise,extension)"
        unless defined $hash and defined $vmpath and defined $enterprise and defined $extension;
    return "Invalid vmpath $vmpath"
        unless -d $vmpath;
    
    # Find the .txt files, compute their MD5sums, and index them
    open my $find, qq(cd '${vmpath}' \&\& nice -n 1 find ${enterprise}/${extension}/ -name 'msg*.txt' -print0 | nice -n 1 xargs -r -0 md5sum |)
        or return "find: $!";

    while(<$find>)
    {
        chomp;
        my ($md5,$location) = split(' ',$_);
        $location =~ s/\.txt$//;
        $hash->{$md5} = $location;        
    }
    close $find;
    return '';
}

# dirname: anything up to (but excluding) the last slash
sub dirname($)
{
    my $t = shift;
    $t =~ s{/[^/]*$}{};
    return $t;
}

# basename: anything after (and excluding) the last slash
sub basename($)
{
    my $t = shift;
    $t =~ s{^.*/}{};
    return $t;
}

# Lock a directory the same way Asterisk does.
# Return 1 if successful, 0 if unsuccessful.
sub dir_lock($)
{
    my $dir_name = shift;
    our $o_link = "$dir_name/.lock-".int(rand(1000000));

    my $lock;

    my $success =
        open( $lock, '>', $o_link )
    and close( $lock )
    and link( $o_link, "$dir_name/.lock" );
    
    unlink( $o_link );
    return $success;
}

sub dir_unlock($)
{
    my $dir_name = shift;
    return unlink( "$dir_name/.lock" );
}

sub new_id($)
{
    my $new_dir = shift;
    my $new_id = 'msg0000';
    while( -e "$new_dir/$new_id.txt" ) { $new_id++; }
    return $new_id;        
}

1;
